package com.dzbh.cdsdriver.ui;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.dzbh.cdsdriver.R;
import com.dzbh.cdsdriver.adapter.NewBillsAdapter;
import com.dzbh.cdsdriver.api.IDealBillsService;
import com.dzbh.cdsdriver.api.IGetBillsService;
import com.dzbh.cdsdriver.model.BillBean;
import com.dzbh.cdsdriver.model.ResultBean;
import com.dzbh.cdsdriver.service.MyLocationService;
import com.dzbh.cdsdriver.utils.BaseResp;
import com.dzbh.cdsdriver.utils.HRetrofitNetHelper;
import com.dzbh.cdsdriver.utils.NetUtil;
import com.dzbh.cdsdriver.utils.Utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

import static android.content.Context.MODE_PRIVATE;

public class BeforeThansFragment extends BaseFragment implements View.OnClickListener {

    private Context mContext;
    private TextView noBillTV;
    private Button gotoWorkBtn;
    private RecyclerView billsLV;
    private SharedPreferences mSharedPreferences;
    private String mName;
    private String mPhone;
    private NewBillsAdapter mNewBillsAdapter;
    private List<BillBean> mDataList;
    private RelativeLayout contentRL;

    @Override
    public void onDetach() {
        super.onDetach();

        try {
            Field childFragmentManager = Fragment.class
                    .getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);

        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            getBills();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mContext = getActivity();
        View view = inflater.inflate(R.layout.fragment_before_trans, null);
        mDataList = new ArrayList<>();
        initView(view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onResume() {
        super.onResume();
        mSharedPreferences = mContext.getSharedPreferences(Utils.FILENAME, MODE_PRIVATE);
        mName = mSharedPreferences.getString(Utils.NAME, "");
        mPhone = mSharedPreferences.getString(Utils.PHONE, "");
        if (null == mNewBillsAdapter) {
            mNewBillsAdapter = new NewBillsAdapter(getActivity());
        }
        billsLV.setAdapter(mNewBillsAdapter);
        getBills();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    private void initView(View v) {
        noBillTV = (TextView) v.findViewById(R.id.nobills);
        billsLV = (RecyclerView) v.findViewById(R.id.listview);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        billsLV.setLayoutManager(manager);
        gotoWorkBtn = (Button) v.findViewById(R.id.towork);
        gotoWorkBtn.setOnClickListener(this);
        contentRL = (RelativeLayout) v.findViewById(R.id.content);
        hideBillView();
    }

    HRetrofitNetHelper.RetrofitCallBack<List<BillBean>> getBillsCallBack = new HRetrofitNetHelper.RetrofitCallBack<List<BillBean>>() {
        @Override
        public void onSuccess(BaseResp<List<BillBean>> baseResp) {
            mDialog.dismiss();
            if(baseResp.getResultCode() != 200){
                showToast(R.string.fail_dealbills);
                return;
            }
            mDataList.clear();
            ArrayList<BillBean> bills = (ArrayList<BillBean>) baseResp.getData();
            if (null == bills || bills.size() <= 0) {
                hideBillView();
                showToast(R.string.no_bills);
                return;
            }
            showBillView();
            mDataList.addAll(bills);
            mNewBillsAdapter.setmDataList(mDataList);
            mNewBillsAdapter.notifyDataSetChanged();

            Intent intent = new Intent(mContext, MyLocationService.class);
            mContext.startService(intent);
            /*PushManager.startWork(getActivity().getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY,
                    "uXdtyBCRxexqvYDISbMtRLlBfG5Lv4s0");
            List<String> tags = new ArrayList<>();
            tags.add("运输中");
            PushManager.setTags(getActivity().getApplicationContext(), tags);*/
        }

        @Override
        public void onFailure(String error) {
            mDialog.dismiss();
            showToast(error);
        }
    };

    HRetrofitNetHelper.RetrofitCallBack<ResultBean> dealBillsCallBack = new HRetrofitNetHelper.RetrofitCallBack<ResultBean>() {
        @Override
        public void onSuccess(BaseResp<ResultBean> baseResp) {
            mDialog.dismiss();
            if(baseResp.getResultCode() == 200) {
                hideBillView();
                showToast(R.string.success_dealbills);
            }else{
                showToast(R.string.fail_dealbills);
            }
        }

        @Override
        public void onFailure(String error) {
            mDialog.dismiss();
            showToast(error);
        }
    };

    // 获取待运单子
    private void getBills(){
        /*mName = "杨志超";
        mPhone ="13585531956";*/
        if(TextUtils.isEmpty(mName) || TextUtils.isEmpty(mPhone)){
            showToast(R.string.unlogin);
            return;
        }
        if(NetUtil.checkNetwork(mContext) == NetUtil.NO_NETWORK){
            showToast(R.string.no_net);
            return;
        }
        mDialog.setMessage(getString(R.string.tips_getBills));
        mDialog.show();
        IGetBillsService getBillsService = retrofitNetHelper.getAPIService(IGetBillsService.class);
        final Call<BaseResp<List<BillBean>>> repos = getBillsService.newBills(mName, mPhone);
        retrofitNetHelper.enqueueCall(repos, getBillsCallBack);
    }

    private void dealBills(){
        if(TextUtils.isEmpty(mName) || TextUtils.isEmpty(mPhone)){
            showToast(R.string.unlogin);
            return;
        }
        if(NetUtil.checkNetwork(mContext) == NetUtil.NO_NETWORK){
            showToast(R.string.no_net);
            return;
        }
        mDialog.setMessage(getString(R.string.tips_dealbills));
        mDialog.show();
        IDealBillsService dealBillsService = retrofitNetHelper.getAPIService(IDealBillsService.class);
        final Call<BaseResp<ResultBean>> reposs = dealBillsService.dealBills(mName, mPhone);
        retrofitNetHelper.enqueueCall(reposs, dealBillsCallBack);
    }

    private void showBillView(){
        contentRL.setVisibility(View.VISIBLE);
        noBillTV.setVisibility(View.GONE);
    }

    private void hideBillView(){
        contentRL.setVisibility(View.GONE);
        noBillTV.setVisibility(View.VISIBLE);
    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.towork) {
            // 接单
            dealBills();
        }
    }
}
